package com.leador.batch.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


import com.leador.assist.DataQueueManager;
import com.leador.module.ILocation;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;


/**
 * Created by lhy on 2016/6/14.
 */
public class DatabaseManager {
    private static DatabaseManager INSTANCE = null;
    private DatabaseHelper databaseHelper;
    private DatabaseManager(Context context){
        databaseHelper = new DatabaseHelper(context);
    }
    public static DatabaseManager getInstance(Context context){
        if(INSTANCE == null){
            synchronized (DatabaseManager.class){
                if(INSTANCE == null){
                    INSTANCE = new DatabaseManager(context);
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 防止重复入库应该入库前先查询再入库
     * @param iLocation
     */
    public void insert(ILocation iLocation){
        synchronized (databaseHelper){
            SQLiteDatabase db=databaseHelper.getWritableDatabase();
            //使用ContentValues添加数据
            ContentValues values=new ContentValues();
            values.put("loc_time",iLocation.getLoc_time());
            values.put("latitude",iLocation.getLatitude());
            values.put("longitude",iLocation.getLongitude());
            values.put("speed",iLocation.getSpeed());
            values.put("status",iLocation.getStatus());
            values.put("extend1",iLocation.getExtend1());
            values.put("service_id",iLocation.getService_id());
            values.put("ak",iLocation.getAk());
            values.put("entity_name",iLocation.getEntity_name());
            db.insert(databaseHelper.DB_TABLE_NAME, null, values);
            db.close();
        }
    }

    public void inserts(){
        synchronized (databaseHelper){
           Deque deque = DataQueueManager.getInstance().iLocationTemp;
            if(deque == null || deque.size() == 0){
                return;
            }
            while (deque.size() > 0){
                ILocation iLocation = (ILocation) deque.poll();
                insert(iLocation);
            }
        }
    }
    public List<ILocation> getSyncData(){
        List<ILocation> trackLocation = new ArrayList<ILocation>();
        long a = 0;
        try {
            //test
            String sqlT = "select count(*) from "+DatabaseHelper.DB_TABLE_NAME;
            SQLiteDatabase db1=databaseHelper.getWritableDatabase();
            Cursor cursor1 = db1.rawQuery(sqlT, null);
            if(cursor1!=null&&cursor1.moveToFirst()){
                a = cursor1.getLong(0);
                cursor1.close();
            }
        }catch (Exception e){

        }

        SQLiteDatabase db=databaseHelper.getWritableDatabase();
        String[] arrayOfString = null;
        String sql = "select * from "+ DatabaseHelper.DB_TABLE_NAME +" limit 0,?" ;
        arrayOfString = new String[] { String.valueOf(a) };
        Cursor cursor = db.rawQuery(sql, arrayOfString);
        if(cursor!=null&&cursor.moveToFirst()){
            do{
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                String loc_time = cursor.getString(cursor.getColumnIndex("loc_time"));
                String latitude = cursor.getString(cursor.getColumnIndex("latitude"));
                String longitude = cursor.getString(cursor.getColumnIndex("longitude"));
                String speed = cursor.getString(cursor.getColumnIndex("speed"));
                String status = cursor.getString(cursor.getColumnIndex("status"));
                String extend1 = cursor.getString(cursor.getColumnIndex("extend1"));
                String extend2 = cursor.getString(cursor.getColumnIndex("extend2"));
                String ak = cursor.getString(cursor.getColumnIndex("ak"));
                String entity_name = cursor.getString(cursor.getColumnIndex("entity_name"));
                String service_id = cursor.getString(cursor.getColumnIndex("service_id"));
                ILocation iLocation = new ILocation();
                iLocation.setId(String.valueOf(id));
                iLocation.setSpeed(speed);
                iLocation.setExtend1(extend1);
                iLocation.setExtend2(extend2);
                iLocation.setLatitude(latitude);
                iLocation.setLoc_time(loc_time);
                iLocation.setLongitude(longitude);
                iLocation.setStatus(status);
                iLocation.setAk(ak);
                iLocation.setService_id(service_id);
                iLocation.setEntity_name(entity_name);
                trackLocation.add(iLocation);
            }while(cursor.moveToNext());
            cursor.close();
        }

        //delete 删除字符串 String[] arrayOfString
        deleteDb(arrayOfString);
        return trackLocation;
    }

    public void getData(){
        long a = 0;
        try {
            //test
            String sqlT = "select count(*) from "+DatabaseHelper.DB_TABLE_NAME;
            SQLiteDatabase db1=databaseHelper.getWritableDatabase();
            Cursor cursor1 = db1.rawQuery(sqlT, null);
            if(cursor1!=null&&cursor1.moveToFirst()){
                a = cursor1.getLong(0);
                cursor1.close();
            }

        }catch (Exception e){

        }

        long length = 30;
        if(a < length){
            length = a;
        }

        try {
            if(length > 0){
                SQLiteDatabase db=databaseHelper.getWritableDatabase();
                String[] arrayOfString = null;
                String sql = "select * from "+ DatabaseHelper.DB_TABLE_NAME +" limit 0,?" ;
                arrayOfString = new String[] { String.valueOf(length) };
                Cursor cursor = db.rawQuery(sql, arrayOfString);
                if(cursor!=null&&cursor.moveToFirst()){
                    do{
                        int id = cursor.getInt(cursor.getColumnIndex("id"));
                        String loc_time = cursor.getString(cursor.getColumnIndex("loc_time"));
                        String latitude = cursor.getString(cursor.getColumnIndex("latitude"));
                        String longitude = cursor.getString(cursor.getColumnIndex("longitude"));
                        String speed = cursor.getString(cursor.getColumnIndex("speed"));
                        String status = cursor.getString(cursor.getColumnIndex("status"));
                        String extend1 = cursor.getString(cursor.getColumnIndex("extend1"));
                        String extend2 = cursor.getString(cursor.getColumnIndex("extend2"));
                        String ak = cursor.getString(cursor.getColumnIndex("ak"));
                        String entity_name = cursor.getString(cursor.getColumnIndex("entity_name"));
                        String service_id = cursor.getString(cursor.getColumnIndex("service_id"));
                        ILocation iLocation = new ILocation();
                        iLocation.setId(String.valueOf(id));
                        iLocation.setSpeed(speed);
                        iLocation.setExtend1(extend1);
                        iLocation.setExtend2(extend2);
                        iLocation.setLatitude(latitude);
                        iLocation.setLoc_time(loc_time);
                        iLocation.setLongitude(longitude);
                        iLocation.setStatus(status);
                        iLocation.setAk(ak);
                        iLocation.setService_id(service_id);
                        iLocation.setEntity_name(entity_name);
                        DataQueueManager.getInstance().setiLocations(iLocation);
                    }while(cursor.moveToNext());
                    cursor.close();
                }
                //delete 删除字符串 String[] arrayOfString
                deleteDb(arrayOfString);
            }
        }catch (Exception e){

        }

        long a1 = 0;
        try{
            String sqlT1 = "select count(*) from "+DatabaseHelper.DB_TABLE_NAME;
            SQLiteDatabase db11=databaseHelper.getWritableDatabase();
            Cursor cursor12 = db11.rawQuery(sqlT1, null);
            if(cursor12!=null&&cursor12.moveToFirst()){
                a1 = cursor12.getLong(0);
            }
        }catch (Exception e){

        }
    };

    public void deleteDb(String[] arrayOfString ){
        if(arrayOfString == null){
            return;
        }
        if(arrayOfString.length == 0){
            return;
        }
        SQLiteDatabase db=databaseHelper.getWritableDatabase();
        String sql = "delete  from "+DatabaseHelper.DB_TABLE_NAME+"  where rowid in(select rowid from "+DatabaseHelper.DB_TABLE_NAME+"  limit 0,?)";
        //调用delete方法，删除数据
        db.execSQL(sql,arrayOfString);
    }

    /**
     * 批量删除
     * @param iLocationList
     */
    public void delete(List<ILocation> iLocationList){
        if(iLocationList == null){
            return;
        }
        SQLiteDatabase db=databaseHelper.getWritableDatabase();
        //调用delete方法，删除数据
        for(ILocation t:iLocationList){
            db.delete(databaseHelper.DB_TABLE_NAME, "id=?", new String[]{t.getId()});
        }
    }

}
